package org.calzz.jajb.converter;

import org.calzz.jajb.JsonDeserializer;
import org.calzz.jajb.JsonSerializer;
import org.calzz.jajb.io.IWriter;
import org.springframework.core.MethodParameter;

/**
 * The default converter for the Java <code>String</code> type.
 * 
 * @author Marek Brodziak <marek.brodziak@gmail.com>
 * @author Piotr Pejas <piotr.pejas@gmail.com>
 * @since Feb 6, 2008
 */
public class StringConverter implements IConverter {

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#canConvert(java.lang.Class)
	 */
	public boolean canConvert(Class<?> clazz) {
		return String.class.equals(clazz) || Character.class.equals(clazz);
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#marshal(java.lang.Object,
	 *      java.lang.String, org.jamjam.jajb.io.IWriter,
	 *      org.jamjam.jajb.JsonSerializer)
	 */
	public void marshal(Object obj, String name, IWriter writer, JsonSerializer serializer) {
		writer.writeKey(name);
		writer.writeString(obj.toString());
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#unmarshal(java.lang.Object,
	 *      java.lang.Class, org.jamjam.jajb.JsonDeserializer)
	 */
	public <T> Object unmarshal(Object env, Class<T> clazz, JsonDeserializer deserializer, MethodParameter methodParam) {
		if (Character.class.equals(clazz) || char.class.equals(clazz)) {
			return env.toString().charAt(0);
		}
		return env.toString();
	}

}
